import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Message } from '@teamix/ui';
import exceed from 'utils/apimap';
import { navigate } from 'utils/router';
import UILessAssociateTask from 'components/UILessAssociateTask';
import utils from 'utils';
import BranchAndTagSelect from 'components/branchAndTagSelect';
import intl from '../../../../../../../locale';
import { getFeature } from 'utils/features';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;
export default class BranchModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      isModalOpen: false,
      task_ids: '',
    };
  }

  handleInputKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.handleOk();
    }
  };

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });
  };

  onCancel = () => {
    this.setState({
      isModalOpen: false,
    });
  };

  formSubmit = (formData, cb) => {
    exceed
      .fetch({
        api: 'project.branches.post.associateTask',
        data: {
          project_id: pathResource.id,
          ...formData,
        },
      })
      .then((result) => {
        Message.success({
          title: intl.get({
            id: 'code-assets.projectBranches.containers.createBranchModal.BranchCreated',
            defaultMessage: '分支新建成功',
          }),
        });

        navigate(`/${pathResource.fullPath}/tree/${utils.revisionEncodeURI(result.name)}`);
      })
      .fail(() => {
        // 接口报错也要回调，以让按钮取消loading状态
        cb && cb('isFail');
      });
  };

  handleOk = () => {
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        if (this.state.task_ids) {
          formData.task_ids = this.state.task_ids;
        }
        this.formSubmit(formData, () => {
          this.setState({ submitting: false });
        });
      }
    });
  };

  // 分支名校验
  nameValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 100) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheLengthOfTheBranch',
          defaultMessage: '分支名长度不能超过100',
        }),
      );
    }

    if (/^[0-9a-fA-F]{40}$/.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotBe',
          defaultMessage: '分支名不允许是40位且字母数字组成。',
        }),
      );
    }

    if (value.indexOf(' ') >= 0) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameIsInvalid',
          defaultMessage: '分支名称不合法',
        }),
      );
    }

    if (value.indexOf('@{') >= 0) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotContain',
          defaultMessage: '分支名称不能包含连续的@{',
        }),
      );
    }

    if (value.indexOf('..') >= 0) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotContain.1',
          defaultMessage: '分支名称不能包含连续的两个点',
        }),
      );
    }

    if (value.indexOf('/') === 0 || value.indexOf('/') === value.length - 1) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotStart',
          defaultMessage: '分支名称不能以 / 开头或结尾',
        }),
      );
    }

    if (/\.lock$/.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotEnd',
          defaultMessage: '分支名称结尾不能是.lock',
        }),
      );
    }

    if (/^\./.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotStart.1',
          defaultMessage: '分支名称不能以 . 开头',
        }),
      );
    }

    if (/^-/.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameCannotStart.2',
          defaultMessage: '分支名称不能以 - 开头',
        }),
      );
    }

    if (/[~^:\\*?[]/.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.TheBranchNameIsInvalid',
          defaultMessage: '分支名称不合法',
        }),
      );
    }

    // const regExp = new RegExp(
    //   "[`~!@#$%^&*()=|{}':;',\\[\\]<>?~！@#￥%……&*（）——+|{}【】《》 ‘；：”“’。，、？]"
    // );
    // if (regExp.test(value) === true) {
    //   callback('非法分支名');
    // }

    // 特殊空白字符过滤
    if (encodeURIComponent(value) === '%E3%80%80') {
      callback(
        intl.get({
          id: 'code-assets.projectBranches.containers.createBranchModal.InvalidBranchName',
          defaultMessage: '非法分支名',
        }),
      );
    }

    callback();
  };

  render() {
    const { init } = this.field;
    const { defaultBranch } = pathResource;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={intl.get({
              id: 'code-assets.src.utils.locale.CreateABranch',
              defaultMessage: '新建分支',
            })}
            visible
            style={{ width: '600px' }}
            onOk={this.handleOk}
            onCancel={this.onCancel}
            onClose={this.onClose}
            okProps={{ loading: !!this.state.submitting }}
          >
            <Form field={this.field} labelAlign="top" className="create-branch-form">
              <FormItem
                label={intl.get({
                  id: 'code-assets.src.utils.locale.BranchName',
                  defaultMessage: '分支名称',
                })}
                required
              >
                <Input
                  {...init('branch_name', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                      { validator: this.nameValidator },
                    ],
                  })}
                  autoFocus
                  onKeyDown={this.handleInputKeyDown}
                  spellCheck={false}
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.projectBranches.containers.createBranchModal.CreateSource',
                  defaultMessage: '创建来源',
                })}
                required
                help={
                  this.field.getState('ref') === 'error'
                    ? this.field.getError('ref')
                    : '填写已存在的分支、标签或提交记录ID'
                }
              >
                {/* 支持tag/commit/branch */}
                <BranchAndTagSelect
                  autoComplete
                  needTagSearch
                  {...init('ref', {
                    initValue: defaultBranch,
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                    ],
                  })}
                  className="br-select"
                  style={{ width: '100%' }}
                  autoWidth
                  {...this.props}
                />
              </FormItem>
              {getFeature('project.associated_projex_workitem') && (
                <Form.Item
                  label={
                    <span>
                      {intl.get({
                        id: 'code-assets.projectBranches.containers.createBranchModal.AssociatedContent',
                        defaultMessage: '关联内容',
                      })}
                    </span>
                  }
                >
                  <UILessAssociateTask
                    useBy="createBranch"
                    onChange={(items) => {
                      if (!items.map) {
                        return;
                      }
                      const task_ids = items.map((item) => {
                        return item._id;
                      });
                      this.setState({
                        task_ids: task_ids.join(','),
                      });
                    }}
                  />
                </Form.Item>
              )}
            </Form>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, {
            onClick: (e) => {
              this.props.trigger.props.onClick && this.props.trigger.props.onClick(e);
              this.showModal();
            },
          })}
      </React.Fragment>
    );
  }
}
